<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="tree shaking 简单理解就是在代码打包时将项目代码中没有用到的代码剔除掉，比如在一个文件中申明了一个工具函数，但是并没有调用它，把这样的代码剔除掉，以减少代码打包体积。">
<meta property="og:type" content="article">
<meta property="og:title" content="如何自己实现一个简单的tree shaking">
<meta property="og:url" content="https://hxy1997.xyz/2021/08/08/%E5%A6%82%E4%BD%95%E8%87%AA%E5%B7%B1%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84tree%20shaking/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="tree shaking 简单理解就是在代码打包时将项目代码中没有用到的代码剔除掉，比如在一个文件中申明了一个工具函数，但是并没有调用它，把这样的代码剔除掉，以减少代码打包体积。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-08-07T16:09:38.000Z">
<meta property="article:modified_time" content="2021-08-08T02:33:59.837Z">
<meta property="article:author" content="hxy">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="tree shaking">
<meta property="article:tag" content="AST">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://hxy1997.xyz/2021/08/08/%E5%A6%82%E4%BD%95%E8%87%AA%E5%B7%B1%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84tree%20shaking/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>如何自己实现一个简单的tree shaking | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2021/08/08/%E5%A6%82%E4%BD%95%E8%87%AA%E5%B7%B1%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84tree%20shaking/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          如何自己实现一个简单的tree shaking
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-08-08 00:09:38 / 修改时间：10:33:59" itemprop="dateCreated datePublished" datetime="2021-08-08T00:09:38+08:00">2021-08-08</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/08/08/%E5%A6%82%E4%BD%95%E8%87%AA%E5%B7%B1%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84tree%20shaking/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/08/08/%E5%A6%82%E4%BD%95%E8%87%AA%E5%B7%B1%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84tree%20shaking/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>tree shaking 简单理解就是在代码打包时将项目代码中没有用到的代码剔除掉，比如在一个文件中申明了一个工具函数，但是并没有调用它，把这样的代码剔除掉，以减少代码打包体积。</p>
<span id="more"></span>

<h3 id="acron"><a href="#acron" class="headerlink" title="acron"></a>acron</h3><p><a href="https://link.zhihu.com/?target=https://github.com/acornjs/acorn">acron</a> </p>
<p>A tiny, fast JavaScript parser, written completely in JavaScript。</p>
<p>这是用js写的js语言的解析器。用它可以将js代码进行词法分析，语法分析，进而得到ast，处理ast得到我们想要的结果。 这里就用acron的能力，进行js的语法分析。</p>
<h3 id="解决思路"><a href="#解决思路" class="headerlink" title="解决思路"></a>解决思路</h3><p>整体思路是，读取一个文件中的代码，调用acron进行语法分析，剔除没有调用过的函数，结果再输出到一个新的文件中。</p>
<h4 id="需要剔除的源代码"><a href="#需要剔除的源代码" class="headerlink" title="需要剔除的源代码"></a>需要剔除的源代码</h4><p>源代码 test.js </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">a, b</span>) =&gt;</span> a + b;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> subtract = <span class="function">(<span class="params">a, b</span>) =&gt;</span> a - b;   <span class="comment">// 这个函数没有被调用，在shaking后，会剔除这个函数</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> num1 = <span class="number">9</span>;</span><br><span class="line"><span class="keyword">const</span> num2 = <span class="number">100</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> result = add(num1, num2);</span><br></pre></td></tr></table></figure>

<h4 id="文件结构"><a href="#文件结构" class="headerlink" title="文件结构"></a>文件结构</h4><p>整个项目的文件结构是</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">project</span><br><span class="line">   src</span><br><span class="line">    |--- index.js   &#x2F;&#x2F; 入口文件</span><br><span class="line">    |--- test.js    &#x2F;&#x2F; 源代码</span><br><span class="line">    |--- visitor.js &#x2F;&#x2F; 处理ast的代码</span><br></pre></td></tr></table></figure>

<h3 id="文件内容"><a href="#文件内容" class="headerlink" title="文件内容"></a>文件内容</h3><p>处理ast的代码 visitor.js </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Visitor</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 访问变量申明</span></span><br><span class="line">    <span class="function"><span class="title">visitVariableDeclaration</span>(<span class="params">node</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        str += node.kind + <span class="string">&#x27; &#x27;</span>;</span><br><span class="line">        str += <span class="built_in">this</span>.visitNodes(node.declarations);</span><br><span class="line">        <span class="keyword">return</span> str + <span class="string">&#x27;\n&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 访问定义的变量名</span></span><br><span class="line">    <span class="function"><span class="title">visitVariableDeclarator</span>(<span class="params">node, kind</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        str += kind ? kind + <span class="string">&#x27; &#x27;</span> : str;</span><br><span class="line">        str += <span class="built_in">this</span>.visitNode(node.id) + <span class="string">&#x27; &#x27;</span>;</span><br><span class="line">        str += <span class="string">&#x27;= &#x27;</span>;</span><br><span class="line">        str += <span class="built_in">this</span>.visitNode(node.init);</span><br><span class="line">        <span class="keyword">return</span> str + <span class="string">&#x27;;&#x27;</span> + <span class="string">&#x27;\n&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 访问标识符</span></span><br><span class="line">    <span class="function"><span class="title">visitIdentifier</span>(<span class="params">node</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        str += node.name;</span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 访问箭头函数</span></span><br><span class="line">    <span class="function"><span class="title">visitArrowFunctionExpression</span>(<span class="params">node</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        str += <span class="string">&#x27;(&#x27;</span>;</span><br><span class="line">        node.params.forEach(<span class="function">(<span class="params">param, index</span>) =&gt;</span> &#123;</span><br><span class="line">            str += <span class="built_in">this</span>.visitNode(param);</span><br><span class="line">            str += (index === node.params.length - <span class="number">1</span>) ? <span class="string">&#x27;&#x27;</span> : <span class="string">&#x27;,&#x27;</span></span><br><span class="line">        &#125;)</span><br><span class="line">        str += <span class="string">&#x27;)&#x27;</span>;</span><br><span class="line">        str += <span class="string">&#x27;=&gt;&#x27;</span>;</span><br><span class="line">        str += <span class="built_in">this</span>.visitNode(node.body);</span><br><span class="line">        <span class="keyword">return</span> str + <span class="string">&#x27;\n&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 访问字符常量</span></span><br><span class="line">    <span class="function"><span class="title">visitLiteral</span>(<span class="params">node</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        str += node.raw;</span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 访问操作符</span></span><br><span class="line">    <span class="function"><span class="title">visitBinaryExpression</span>(<span class="params">node</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        str += <span class="built_in">this</span>.visitNode(node.left);</span><br><span class="line">        str += node.operator;</span><br><span class="line">        str += <span class="built_in">this</span>.visitNode(node.right);</span><br><span class="line">        <span class="keyword">return</span> str + <span class="string">&#x27;\n&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">visitCallExpression</span>(<span class="params">node</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        str += <span class="built_in">this</span>.visitNode(node.callee);</span><br><span class="line">        str += <span class="string">&#x27;(&#x27;</span>;</span><br><span class="line">        node.arguments.forEach(<span class="function">(<span class="params">param, index</span>) =&gt;</span> &#123;</span><br><span class="line">            str += <span class="built_in">this</span>.visitNode(param);</span><br><span class="line">            str += (index === node.arguments.length - <span class="number">1</span>) ? <span class="string">&#x27;&#x27;</span>:<span class="string">&#x27;,&#x27;</span>;</span><br><span class="line">        &#125;)</span><br><span class="line">        str += <span class="string">&#x27;)&#x27;</span>;</span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">// 访问多个节点</span></span><br><span class="line">    <span class="function"><span class="title">visitNodes</span>(<span class="params">nodes</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span></span><br><span class="line">        nodes.forEach(<span class="function"><span class="params">node</span> =&gt;</span> &#123;</span><br><span class="line">            str += <span class="built_in">this</span>.visitNode(node);</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">// 访问单个节点</span></span><br><span class="line">    <span class="function"><span class="title">visitNode</span>(<span class="params">node</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        <span class="keyword">switch</span> (node.type) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;VariableDeclaration&#x27;</span>:</span><br><span class="line">                str += <span class="built_in">this</span>.visitVariableDeclaration(node);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;VariableDeclarator&#x27;</span>:</span><br><span class="line">                str += <span class="built_in">this</span>.visitVariableDeclarator(node);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;Identifier&#x27;</span>:</span><br><span class="line">                str += <span class="built_in">this</span>.visitIdentifier(node);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;ArrowFunctionExpression&#x27;</span>:</span><br><span class="line">                str += <span class="built_in">this</span>.visitArrowFunctionExpression(node);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;BinaryExpression&#x27;</span>:</span><br><span class="line">                str += <span class="built_in">this</span>.visitBinaryExpression(node);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;Literal&#x27;</span>:</span><br><span class="line">                str += <span class="built_in">this</span>.visitLiteral(node);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;CallExpression&#x27;</span>:</span><br><span class="line">                str += <span class="built_in">this</span>.visitCallExpression(node);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">// 访问body元素</span></span><br><span class="line">    <span class="function"><span class="title">run</span>(<span class="params">body</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">        <span class="comment">// 遍历</span></span><br><span class="line">        str += <span class="built_in">this</span>.visitNodes(body);</span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = Visitor;</span><br></pre></td></tr></table></figure>

<p>入口文件 index.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> acron = <span class="built_in">require</span>(<span class="string">&#x27;acorn&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> Visitor = <span class="built_in">require</span>(<span class="string">&#x27;./visitor&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> visitor = <span class="keyword">new</span> Visitor();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取命令行参数</span></span><br><span class="line"><span class="keyword">const</span> args = process.argv[<span class="number">2</span>];</span><br><span class="line"><span class="comment">// 读取文件缓存</span></span><br><span class="line"><span class="keyword">const</span> buffer = fs.readFileSync(args).toString();</span><br><span class="line"><span class="comment">// 解析成抽象语法树</span></span><br><span class="line"><span class="keyword">const</span> body = acron.parse(buffer).body;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> decls = <span class="keyword">new</span> <span class="built_in">Map</span>(); <span class="comment">// 记录所有申明过的变量</span></span><br><span class="line"><span class="keyword">const</span> calledDecls = []; <span class="comment">// 记录调用过的函数</span></span><br><span class="line"><span class="keyword">let</span> code = []; <span class="comment">// 存放源代码</span></span><br><span class="line"></span><br><span class="line">body.forEach(<span class="function"><span class="params">node</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (node.type === <span class="string">&#x27;VariableDeclaration&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> kind = node.kind;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">const</span> decl <span class="keyword">of</span> node.declarations) &#123;</span><br><span class="line">            <span class="comment">// todo</span></span><br><span class="line">            decls.set(visitor.visitNode(decl.id), visitor.visitVariableDeclarator(decl, kind));</span><br><span class="line">            <span class="keyword">if</span> (decl.init.type === <span class="string">&#x27;CallExpression&#x27;</span>) &#123;</span><br><span class="line">                calledDecls.push(visitor.visitIdentifier(decl.init.callee));</span><br><span class="line">                <span class="keyword">const</span> args = decl.init.arguments;</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">const</span> arg <span class="keyword">of</span> args) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (arg.type === <span class="string">&#x27;Identifier&#x27;</span>) &#123;</span><br><span class="line">                        calledDecls.push(visitor.visitNode(arg));</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (node.type === <span class="string">&#x27;Identifier&#x27;</span>) &#123;</span><br><span class="line">        calledDecls.push(node.name);</span><br><span class="line">    &#125;</span><br><span class="line">    code.push(visitor.run([node]));</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">code = calledDecls.map(<span class="function"><span class="params">c</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> decls.get(c);</span><br><span class="line">&#125;).join(<span class="string">&#x27;&#x27;</span>);</span><br><span class="line"></span><br><span class="line">fs.writeFileSync(__dirname + <span class="string">&#x27;/test.shaked.js&#x27;</span>, code);</span><br></pre></td></tr></table></figure>

<h3 id="执行项目"><a href="#执行项目" class="headerlink" title="执行项目"></a>执行项目</h3><p>在命令行中执行</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node src/index.js src/test.js</span><br></pre></td></tr></table></figure>

<p>得到test.shaked.js 文件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">a, b</span>)=&gt;</span>a+b;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> num1 = <span class="number">9</span>;</span><br><span class="line"><span class="keyword">const</span> num2 = <span class="number">100</span>;</span><br></pre></td></tr></table></figure>

<p>至此，一个简单的tree shaking就做完了。</p>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/javascript/" rel="tag"><i class="fa fa-tag"></i> javascript</a>
              <a href="/tags/tree-shaking/" rel="tag"><i class="fa fa-tag"></i> tree shaking</a>
              <a href="/tags/AST/" rel="tag"><i class="fa fa-tag"></i> AST</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/07/18/%E9%B2%A8%E9%B1%BC%E5%93%A5%E7%9A%84%E5%89%8D%E7%AB%AF%E9%9D%A2%E8%AF%95%E6%95%B4%E7%90%86/" rel="prev" title="鲨鱼哥的前端面试整理">
      <i class="fa fa-chevron-left"></i> 鲨鱼哥的前端面试整理
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/08/22/TypeScript%20%E4%B8%AD%E7%B1%BB%E5%9E%8B%20any%EF%BC%8Cvoid%EF%BC%8Cunknown%EF%BC%8Cnever%E4%B9%8B%E9%97%B4%E7%9A%84%E5%8C%BA%E5%88%AB/" rel="next" title="TypeScript 中类型 any，void，unknown，never之间的区别">
      TypeScript 中类型 any，void，unknown，never之间的区别 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#acron"><span class="nav-text">acron</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E6%80%9D%E8%B7%AF"><span class="nav-text">解决思路</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%9C%80%E8%A6%81%E5%89%94%E9%99%A4%E7%9A%84%E6%BA%90%E4%BB%A3%E7%A0%81"><span class="nav-text">需要剔除的源代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E7%BB%93%E6%9E%84"><span class="nav-text">文件结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E5%86%85%E5%AE%B9"><span class="nav-text">文件内容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%A7%E8%A1%8C%E9%A1%B9%E7%9B%AE"><span class="nav-text">执行项目</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
